package com.my.screenadapter.net;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.my.screenadapter.MyApplication;
import com.my.screenadapter.R;
import com.my.screenadapter.net.okhttpDwonload.DonwloadResponseListener;
import com.my.screenadapter.net.okhttpDwonload.OKHttpUtils;
import com.my.screenadapter.net.retrofit.RetrofitActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 张英杰 on 2017/2/16.
 * 1. mainfest 建立provider
 * 2. res 建立 xml  建立file_paths.xml
 * 3  intent不同版本不同引用
 * 7.0自动更新文章
 * http://www.czhzero.com/2016/12/21/how-to-install-apk-on-Android7-0/
 * http://blog.csdn.net/pkandroid/article/details/53716719
 * 7.0文章：
 * http://blog.csdn.net/fengyuzhengfan/article/details/52688232
 * https://developer.android.google.cn/about/versions/nougat/android-7.0-changes.html
 * 项目:https://github.com/bingoogolapple/BGAUpdate-Android
 * <p>
 * Android OkHttp文件上传与下载的进度监听扩展
 * http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0904/3416.html
 * https://github.com/lizhangqu/CoreProgress
 */

public class DownLoadActivity extends AppCompatActivity {
    private static final String TAG = "DownLoadActivity";
    private Button startDownload;
    //    private String DownLoadUrl = "http://192.168.0.133/MyTest.apk";
//    private String DownLoadUrl = "http://zj.cdn.beeboxes.com/download/rom/abcd.tar.gz";//蜂盒包
    private String DownLoadUrl = "http://zj.cdn.beeboxes.com/download/rom/ZhiAnZongDui_1.6.6.29.tar.gz";//蜂盒包
    private String LocalAddress = Environment.getExternalStorageDirectory() + File.separator + "TestJ.apk";

    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            // 打印Log   ComponentName到底是什么
            Log.i(TAG, "componentName = " + componentName.getClassName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

        } else {
            Toast.makeText(context.getApplicationContext(), "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 判读版本是否在7.0以上 自动更新
     * 安装APK文件
     */
    public static void installApk(Context context, File file) {
        if (context == null || (!file.exists())) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            context.startActivity(intent);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        initView();
    }

    private void initView() {
        startDownload = (Button) findViewById(R.id.btnStart);
        startDownload.setText("开始Okhttp下载7.0兼容并安装");
        final String netApkUrl = "https://d.qiezzi.com/qiezi-clinic.apk";
        startDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startOkHttp(0);
//                startOkHttpDownLoad(netApkUrl);
                startOkHttpDownLoad(DownLoadUrl);
//                installApk(DownLoadActivity.this, new File(LocalAddress));
            }
        });
        findViewById(R.id.retrofit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(DownLoadActivity.this, RetrofitActivity.class));
            }
        });
        findViewById(R.id.browser).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openBrowser(MyApplication.getContext(), DownLoadUrl);
            }
        });
        findViewById(R.id.browser2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openBrowser(MyApplication.getContext(), netApkUrl);
            }
        });

    }

    private void startOkHttpDownLoad(String url) {

        String path = getFilesDir().getAbsolutePath();
//        String path = Environment.getExternalStorageDirectory().getPath();
        OKHttpUtils.instance().donwloadFile(path, url, "abc.apk", new DonwloadResponseListener() {
            @Override
            public void OnSuccess(long bytesRead, long contentLength, boolean done) {
                Log.i(TAG, "OnSuccess  bytesRead==" + bytesRead + "  contentLength==" + contentLength + "  done" + done);
                toastOnUiThread("OnSuccess  bytesRead==" + bytesRead + "  contentLength==" + contentLength + "  done" + done);
                //                pbTestDownload.setProgress((int) ((100 * bytesRead) / contentLength));
            }

            @Override
            public void onfailure() {
                Log.i(TAG, "onfailure  ");
                toastOnUiThread("下载失败");

//                showToast(TestListActivity.this, "下载失败");
            }

            @Override
            public void onSuccess(final File fileName) {
                Log.i(TAG, "Success  " + fileName.toString());
                final String toast = "下载成功了" + fileName.getName();
                toastOnUiThread(toast);

//                showToast(TestListActivity.this, "下载成功" + fileName);
            }
        });
    }

    private void toastOnUiThread(final String toast) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(DownLoadActivity.this, toast, Toast.LENGTH_SHORT).show();
            }
        });
    }

    //    http://blog.csdn.net/itachi85/article/details/51190687
    private void startOkHttp(final int type) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request mRequestOkGet = new Request.Builder()
                .url(DownLoadUrl)
                .method("GET", null) //可以省略，默认是GET请求
                .build();
        Call mCall = mOkHttpClient.newCall(mRequestOkGet);
        mCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = null;
                try {
                    File file = new File(LocalAddress);
                    if (file.exists()&&file.length()>0){
                        file.delete();
                    }
                    fileOutputStream = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.flush();
                    Log.i(TAG,"download over file length== "+(file.length())/(1024*1024)+"MB");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}
